﻿using System;
using System.Collections.Generic;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Interop;
using QQTools.Core.Enums.ForwardGroupMessage;
using QQTools.Data.Enums.ForwardGroupMessage;
using QQTools.Data.Enums.SendGroupMessage;
using QQTools.Data.Models;
using QQTools.Data.Plus;
using QQTools.Data.Repositories.ForwardGroupMessage;
using QQTools.Logging;
using QQTools.Services.Automation;


namespace QQTools.Services.Tasks
{
    public class ForwardGroupMsgServices : BaseTaskManager<ForwardGroupMsgQQModel>
    {

        private readonly object _lock = new object();
        public static ForwardGroupMsgQQRepository _forwardGroupMsgQQRepository;
        public static ForwardGroupMsgRepository _forwardGroupMsgRepository;
        private MainForm _form;

        public ForwardGroupMsgServices(ForwardGroupMsgQQRepository forwardGroupMsgQQRepository, ForwardGroupMsgRepository forwardGroupMsgRepository, MainForm form)
        {
            _forwardGroupMsgQQRepository = forwardGroupMsgQQRepository;
            _forwardGroupMsgRepository = forwardGroupMsgRepository;

            _form = form;
        }

        public async Task Start(List<QQModel> qqList, ForwardGroupMsgType msgType, int forwardIntervalStart, int forwardIntervalEnd, int batchRecipientCount, int accountTotalForward, CancellationToken token)
        {
            // 重置所有任务的消息类型为 msgType
            _forwardGroupMsgRepository.ResetMsgTypeAsync(msgType);
            // 1. 获取所有任务QQ账号
            List<ForwardGroupMsgQQModel> forwardGroupMsgQQModels = await _forwardGroupMsgQQRepository.GetAllAsync();

            // 获取该QQ的所有群, 并且高亮第一个群号
            _form.UpdateListViewForwardGroupMsg(qq: forwardGroupMsgQQModels.FirstOrDefault()?.QQ);
            string msg;

            while (true)
            {
                if (token.IsCancellationRequested)
                {
                    LogManager.Info("[转发] 任务已取消3");
                    break;
                }
                // 如果所有任务QQ的群没有需要发送的群时,任务结束
                int unusedCount = await _forwardGroupMsgRepository.GetCountByStatusAsync(ForwardGroupMsgStatus.NotStarted);
                if (unusedCount <= 0)
                {
                    msg = "[转发] 所有群聊都已发送完毕, 任务已完成";
                    _form.UpdateStatusStrip(msg);
                    LogManager.Info(msg);
                    break;
                }
                forwardGroupMsgQQModels = await _forwardGroupMsgQQRepository.GetAllAsync();
                // 2.如果所有任务QQ的发送数量达到预设, 任务结束
                int finishedCount = 0;
                foreach (var qqItem in forwardGroupMsgQQModels)
                {
                    if (token.IsCancellationRequested)
                    {
                        LogManager.Info("[转发] 任务已取消4");
                        break;
                    }
                    if (accountTotalForward > 0 && qqItem.ForwardCount >= accountTotalForward)
                    {// 发送数量达标
                        msg = $"[转发] QQ:{qqItem.QQ} 进度:{qqItem.ForwardCount}/{accountTotalForward} 任务已完成";
                        _form.UpdateStatusStrip(msg);
                        LogManager.Info(msg);
                        finishedCount++;
                    }
                    else
                    { // 数量不够走这里
                        unusedCount = await _forwardGroupMsgRepository.GetCountByQQAndStatusAsync(qqItem.QQ, ForwardGroupMsgStatus.NotStarted);
                        if (unusedCount <= 0) // 或没有需要发送的群, 也算达标
                        {
                            finishedCount++;
                            msg = $"[转发] QQ:{qqItem.QQ} 名下所有群聊都已发送完毕, 任务已完成";
                            _form.UpdateStatusStrip(msg);
                            LogManager.Info(msg);
                        }
                        else
                        {   // 数量不够, 且还有未发送的群聊, 走这里判断是否离线
                            int pid = qqList.FirstOrDefault(q => q.QQ == qqItem.QQ)?.LastPid ?? 0;
                            bool isOnline = QQPlus.IsOnline(qqItem.QQ, pid);
                            // QQ离也算达标
                            if (isOnline == false)
                            {
                                finishedCount++;
                                msg = $"[转发] QQ:{qqItem.QQ} 已离线, 任务已完成";
                                _form.UpdateStatusStrip(msg);
                                LogManager.Info(msg);
                            }
                            // 加点延迟,防止QQ崩溃
                            await Task.Delay(200);
                        }

                    }
                }
                if (finishedCount >= forwardGroupMsgQQModels.Count)
                {
                    msg = "[转发] 所有任务已完成";
                    _form.UpdateStatusStrip(msg);
                    LogManager.Info(msg);
                    return;
                }

                // 1.遍历QQ列表
                foreach (var qqItem in forwardGroupMsgQQModels)
                {
                    // 标记当前QQ为在线
                    var qqOnline = true;
                    if (token.IsCancellationRequested)
                    {
                        LogManager.Info("[转发] 任务已取消2");
                        break;
                    }
                    string qq = qqItem.QQ;

                    // UI更新任务:QQ列表, 并将当前QQ高亮
                    _form.UpdateListViewForwardGroupMsgQQ(qq: qq);


                    // 从qqList 获取对应qq的pid
                    int pid = qqList.FirstOrDefault(q => q.QQ == qq)?.LastPid ?? 0;
                    if (pid == 0)
                    {
                        LogManager.Error($"[转发] 未找到QQ:{qq} 的pid");
                        continue;
                    }

                    //bool isOnline = QQPlus.IsOnline(qqItem.QQ, pid);
                    //// QQ离也算达标
                    //if (isOnline == false)
                    //{
                    //    msg = $"[转发] QQ:{qqItem.QQ} 已离线, 跳过";
                    //    _form.UpdateStatusStrip(msg);
                    //    continue;
                    //}

                    // 判断转发数量是否达标
                    // 判断转发数量是否超出预设
                    if (accountTotalForward > 0 && qqItem.ForwardCount >= accountTotalForward)
                    {
                        // 保存QQ列表进度
                        await _forwardGroupMsgQQRepository.UpdateAsync(qqItem);
                        msg = $"[转发] QQ:{qqItem.QQ} 进度:{qqItem.ForwardCount}/{accountTotalForward} 任务已完成";
                        _form.UpdateStatusStrip(msg);
                        LogManager.Info(msg);
                        continue;
                    }


                    // 从数据库中获取当前QQ对应的群列表
                    List<ForwardGroupMsgModel> forwardGroupMsgModelList = await _forwardGroupMsgRepository.GetByQQAsync(qq);

                    // 取一条任务
                    ForwardGroupMsgModel groupInfo = await _forwardGroupMsgRepository.GetAndLockNextForwardGroupAsync(qq);
                    if (groupInfo == null)
                    {
                        msg = $"[转发] {qq} 没有需要发送的群 切换下一个QQ";
                        _form.UpdateStatusStrip(msg);
                        LogManager.Info(msg);
                        continue;
                    }

                    // 获取总任务数
                    int totalGroup = await _forwardGroupMsgRepository.GetCountByQQAsync(qq);
                    // 默认当前转发送次数0
                    //int currentGroupSendCount = 0;

                    if (token.IsCancellationRequested)
                    {
                        LogManager.Info("[转发] 任务已取消1");
                        break;
                    }
                    msg = $"[转发] QQ:{qq} 群:{groupInfo.GroupNumber} 开始发送, 类型:{msgType.ToString()} ";
                    LogManager.Info(msg);
                    // UI更新:状态栏
                    _form.UpdateStatusStrip(msg);
                    // UI更新任务:群列表状态,并将当前群号高亮
                    _form.UpdateListViewForwardGroupMsg(groupInfo);
                    // 如果发送次数大于重试次数则跳过
                    if (groupInfo.ForwardCount > groupInfo.RetryCount)
                    {
                        msg = $"[转发] 发送失败 QQ:{qq} 的群:{groupInfo.GroupNumber} 已经重试:{groupInfo.ForwardCount}/{groupInfo.RetryCount}次, 跳过";
                        _form.UpdateStatusStrip(msg);
                        LogManager.Error(msg);
                        // 更新任务状态
                        await _forwardGroupMsgRepository.UpdateStatusByQQAndGroupNumberAsync(groupInfo.QQ, groupInfo.GroupNumber, ForwardGroupMsgStatus.Failed);
                        continue;
                    }


                    // 模拟转发消息
                    ForwardGroupMsgAuto forwardGroupMsgAuto = new ForwardGroupMsgAuto(pid);
                    // 默认发送失败
                    ForwardGroupMsgResult result = ForwardGroupMsgResult.Faild;

                    for (int attempt = 1; attempt <= 3; attempt++)
                    {
                        if (token.IsCancellationRequested)
                        {
                            LogManager.Info("[转发] 任务已取消2220");
                            break;
                        }
                        // 实际发送消息

                        (result, qqItem.ResourceIndex) = await forwardGroupMsgAuto.ForwardGroupMsg(groupInfo.GroupNumber, msgType.ToString(), token, attempt);
                        if (result == ForwardGroupMsgResult.Success)
                        {
                            break;
                        }
                        else if (result == ForwardGroupMsgResult.ResourceNotFound)
                        {
                            msg = $"[转发] QQ:{qq} 群:{groupInfo.GroupNumber} 分类:{msgType.ToString()} 的资源不存在, 第{attempt}次发送失败, 重试中...";
                            // 资源没找到, 重置资源下标
                            qqItem.ResourceIndex = 1;
                            await _forwardGroupMsgQQRepository.UpdateAsync(qqItem);
                        }
                        else if (result == ForwardGroupMsgResult.QQOffline)
                        {
                            msg = $"[转发] QQ:{qq} 离线 群:{groupInfo.GroupNumber} 分类:{msgType.ToString()} 下标:{qqItem.ResourceIndex} 第{attempt}次发送失败";

                            break;
                        }
                        else
                        {
                            msg = $"[转发] QQ:{qq} 群:{groupInfo.GroupNumber} 分类:{msgType.ToString()} 下标:{qqItem.ResourceIndex} 第{attempt}次发送失败, 重试中...";

                        }
                        LogManager.Error(msg);
                        _form.UpdateStatusStrip(msg);
                    }

                    if (result == ForwardGroupMsgResult.Success)
                    {
                        // 资源索引加1
                        qqItem.ResourceIndex += 1;
                        // 转发成功,QQ成功次数+1
                        qqItem.ForwardCount++;
                        // 重置当前转发送次数
                        groupInfo.ForwardCount = 0;
                        groupInfo.Status = ForwardGroupMsgStatus.Success;
                        // 更新转发任务状态:成功
                        await _forwardGroupMsgRepository.UpdateStatusByQQAndGroupNumberAsync(groupInfo.QQ, groupInfo.GroupNumber, ForwardGroupMsgStatus.Success);
                        msg = $"[转发] QQ:{qq} 群:{groupInfo.GroupNumber} 分类:{msgType.ToString()} 下标:{qqItem.ResourceIndex} 发送成功, 进度:{qqItem.ForwardCount}/{accountTotalForward}";
                    }
                    else
                    {
                        qqItem.FailedCount++;
                        groupInfo.ForwardCount++;
                        groupInfo.Status = ForwardGroupMsgStatus.Failed;
                        // 更新转发任务状态:失败
                        await _forwardGroupMsgRepository.UpdateStatusByQQAndGroupNumberAsync(groupInfo.QQ, groupInfo.GroupNumber, ForwardGroupMsgStatus.Failed);

                        if (result == ForwardGroupMsgResult.QQOffline)
                        {
                            // 标记为离线
                            qqOnline = false;
                        }
                        else
                        {
                            msg = $"[转发] QQ:{qq} 群:{groupInfo.GroupNumber} 分类:{msgType.ToString()} 下标:{qqItem.ResourceIndex} 发送失败，达到最大重试次数！, 进度:{qqItem.ForwardCount}/{accountTotalForward}";
                        }
                    }

                    // 保存QQ列表进度
                    await _forwardGroupMsgQQRepository.UpdateAsync(qqItem);
                    // 保存群列表进度
                    await _forwardGroupMsgRepository.UpdateAsync(groupInfo);

                    // UI更新任务:QQ列表状态, 并将当前QQ高亮
                    _form.UpdateListViewForwardGroupMsgQQ(qq: qq);
                    // UI更新任务:群列表状态,并将当前群号高亮
                    _form.UpdateListViewForwardGroupMsg(groupInfo);

                    if (qqOnline == false)
                    { // QQ离线结束
                        _form.UpdateStatusStrip(msg);
                        LogManager.Info(msg);
                        continue;
                    }

                    int interval = new Random().Next(forwardIntervalStart, forwardIntervalEnd + 1);
                    LogManager.Info($"{msg} 距离发送还剩: {interval} 秒");
                    await _form.StartCountdown($"{msg} 距离发送还剩:", interval, token, $"{msg} 任务停止", null);

                }
            }
        }


        /// <summary>
        /// 添加任务到任务列表
        /// </summary>
        public override void AddTask(ForwardGroupMsgQQModel task)
        {
            //lock (_lock)
            //{
            //    await _forwardGroupMsgQQRepository.AddOrUpdateAsync(task);
            //    runningTasks[task.TaskId] = task;
            //}
        }

        /// <summary>
        /// 启动任务（支持恢复）
        /// </summary>
        public override void StartTask(string taskId)
        {
            //lock (_lock)
            //{
            //    var task = _forwardGroupMsgRepository.LoadTask(taskId);
            //    if (task == null)
            //    {
            //       // MessageBox.Show("任务不存在！");
            //        return;
            //    }

            //    var history = _forwardGroupMsgRepository.LoadHistory(taskId);
            //    if (history != null && !string.IsNullOrEmpty(history.LastSentGroupId))
            //    {
            //        // 恢复任务
            //        task.CurrentGroupIndex = task.Groups.FindIndex(g => g.GroupId == history.LastSentGroupId);
            //    }

            //    runningTasks[taskId] = task;
            //    Task.Run(() => ExecuteTaskAsync(task));
            //}
        }

        /// <summary>
        /// 暂停任务
        /// </summary>
        public override void PauseTask(string taskId)
        {
            //lock (_lock)
            //{
            //    if (!runningTasks.ContainsKey(taskId)) return;

            //    var task = runningTasks[taskId];
            //    task.Status = "已暂停";
            //    _forwardGroupMsgRepository.SaveTask(task);
            //    UpdateUI(task);
            //}
        }

        /// <summary>
        /// 恢复任务
        /// </summary>
        public override void ResumeTask(string taskId)
        {
            //lock (_lock)
            //{
            //    if (!runningTasks.ContainsKey(taskId)) return;

            //    var task = runningTasks[taskId];
            //    task.Status = "进行中";
            //    _forwardGroupMsgRepository.SaveTask(task);
            //    Task.Run(() => ExecuteTaskAsync(task));
            //}
        }


        /// <summary>
        /// 停止任务
        /// </summary>
        public override void StopTask(string taskId)
        {
            //lock (_lock)
            //{
            //    if (!runningTasks.ContainsKey(taskId)) return;

            //    var task = runningTasks[taskId];
            //    task.Status = "已停止";
            //    _forwardGroupMsgRepository.SaveTask(task);
            //    runningTasks.Remove(taskId);
            //    UpdateUI(task);
            //}
        }

        /// <summary>
        /// 执行任务的核心逻辑
        /// </summary>
        protected override async Task ExecuteTaskAsync(ForwardGroupMsgQQModel task)
        {

            await Task.Delay(100);
            //for (int i = task.CurrentGroupIndex; i < task.Groups.Count; i++)
            //{
            //    var group = task.Groups[i];
            //    try
            //    {
            //        SendMessage(group, task.MessageContent);
            //        task.Status = $"已发送到 {group.GroupName}";
            //        task.CurrentGroupIndex = i + 1;

            //        // 保存历史记录
            //        _forwardGroupMsgRepository.SaveHistory(new TaskHistory
            //        {
            //            TaskId = task.TaskId,
            //            LastSentGroupId = group.GroupId,
            //            LastSentTime = DateTime.Now
            //        });

            //        // 更新UI
            //        UpdateUI(task);

            //        await Task.Delay(100); // 模拟异步发送
            //    }
            //    catch (Exception ex)
            //    {
            //        task.Status = $"发送失败: {ex.Message}";
            //        break;
            //    }
            //}

            //task.Status = "已完成";
            //UpdateUI(task);
        }

        /// <summary>
        /// 更新UI状态
        /// </summary>
        protected override void UpdateUI(ForwardGroupMsgQQModel task)
        {
            // 使用Invoke更新UI线程
            //Application.Current.Dispatcher.Invoke(() =>
            //{
            //    // 更新UI状态（需要在WinForms中绑定具体控件）
            //});
            _form.Invoke((MethodInvoker)delegate
            {
                // 更新UI状态（需要在WinForms中绑定具体控件）
            });


        }



    }
}
